package com.example.demo.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * @Auther: miaoguoxin
 * @Date: 2020/3/18 20:27
 * @Description:
 */
@Import(JacksonCustomConfiguration.JacksonBuilderConfiguration.class)
public class JacksonCustomConfiguration {

    @Autowired
    private ObjectMapper objectMapper;

    @PostConstruct
    public void init(){
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory()
                .withSerializerModifier(new NullBeanSerializerModifier()));
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }


    static class JacksonBuilderConfiguration {
        @Bean
        @ConditionalOnClass(JavaTimeModule.class)
        Jackson2ObjectMapperBuilderCustomizer customizeLocalDateTimeFormat(){
            return jacksonObjectMapperBuilder -> {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
            };
        }
    }

    /**
     * Description: 此modifier主要做的事情为：
     * 当序列化类型为array，list、set时，当值为空时，序列化成[]
     * 为数值类型时，当值为空时，序列化成0
     * 为字符类型时，当值为空时，序列化成“”
     *
     */
    public static class NullBeanSerializerModifier extends BeanSerializerModifier {

        private JsonSerializer<Object> arrayJsonSerializer = new ArrayJsonSerializer();
        private JsonSerializer<Object> strJsonSerializer = new StrJsonSerializer();
        private JsonSerializer<Object> dateJsonSerializer = new DateJsonSerializer();
        private JsonSerializer<Object> numberJsonSerializer = new NumJsonSerializer();
        private JsonSerializer<Object> mapJsonSerializer = new MapJsonSerializer();
        @Override
        public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
                                                         List<BeanPropertyWriter> beanProperties) {
            // 循环所有的beanPropertyWriter
            for (BeanPropertyWriter writer : beanProperties) {
                // 判断字段的类型，如果是array，list，set则注册nullSerializer
                if (isArrayType(writer)) {
                    //给writer注册一个自己的nullSerializer
                    writer.assignNullSerializer(arrayJsonSerializer);
                } else if (isDate(writer)) {
                   // writer.assignNullSerializer(dateJsonSerializer);
                } else if (isNumber(writer)) {
                    writer.assignNullSerializer(numberJsonSerializer);
                } else if (isStr(writer)) {
                    writer.assignNullSerializer(strJsonSerializer);
                } else if (isMap(writer)){
                    writer.assignNullSerializer(mapJsonSerializer);
                }
            }
            return beanProperties;
        }

        /**
         * 数组以及集合序列化实现类
         */
        public class ArrayJsonSerializer extends JsonSerializer<Object> {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
                if (value == null) {
                    jgen.writeStartArray();
                    jgen.writeEndArray();
                } else {
                    jgen.writeObject(value);
                }
            }
        }

        /**
         * 日期序列化实现类
         */
        public class DateJsonSerializer extends JsonSerializer<Object> {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
                if (value == null) {
                    jgen.writeNumber(0);
                } else {
                    jgen.writeObject(value);
                }
            }
        }

        /**
         * 字符串序列化实现类
         */
        public class StrJsonSerializer extends JsonSerializer<Object> {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
                if (value == null) {
                    jgen.writeString("");
                } else {
                    jgen.writeObject(value);
                }
            }
        }

        /**
         * 数字序列化实现类
         */
        public class NumJsonSerializer extends JsonSerializer<Object> {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
                if (value == null) {
                    jgen.writeNumber(0);
                } else {
                    jgen.writeObject(value);
                }
            }
        }

        /**
         * 数字序列化实现类
         */
        public class MapJsonSerializer extends JsonSerializer<Object> {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
                if (value == null) {
                    jgen.writeObject(new HashMap<>());
                } else {
                    jgen.writeObject(value);
                }
            }
        }

        /**
         * 判断数组类型
         * @param writer
         * @return
         */
        boolean isArrayType(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
        }

        /**
         * 判断数字类型
         * @param writer
         * @return
         */
        boolean isNumber(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return clazz.equals(Short.class) || clazz.equals(Integer.class)
                    || clazz.equals(Long.class) || clazz.equals(BigDecimal.class)
                    || clazz.equals(Double.class) || clazz.equals(Float.class);
        }

        /**
         * 判断字符类型
         * @param writer
         * @return
         */
        boolean isStr(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return clazz.equals(String.class) || clazz.equals(Character.class)
                    || clazz.equals(StringBuilder.class) || clazz.equals(StringBuffer.class);
        }

        /**
         * 判断字符类型
         * @param writer
         * @return
         */
        boolean isMap(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return Map.class.isAssignableFrom(clazz) ;
        }

        /**
         * 判断日期类型
         * @param writer
         * @return
         */
        boolean isDate(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return clazz.equals(Date.class) || clazz.equals(LocalDateTime.class) || clazz.equals(LocalDate.class);
        }
    }

    public static void main(String[] args) {
        System.out.println(Collection.class.isAssignableFrom(Map.class));
    }
}
